<template>
  <div class="workflow-page">
    <!-- 顶部导航 -->
    <el-breadcrumb separator="/" class="breadcrumb">
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item>AI能力</el-breadcrumb-item>
      <el-breadcrumb-item>工作流</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 搜索栏和右上角按钮 -->
    <div class="search-bar">
      <el-form :inline="true" size="mini" class="search-form">
        <el-form-item label="名称：">
          <el-input
            v-model="search.name"
            placeholder="请输入工作流名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="英文名称：">
          <el-input
            v-model="search.ename"
            placeholder="请输入英文名称,不允许含中文"
            clearable
            class="ename-input"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
      <div class="right-btns">
        <el-button
          type="primary"
          plain
          icon="el-icon-upload"
          class="top-btn white-text-btn"
          @click="openImportDialog"
          >导入工作流</el-button
        >
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          class="top-btn white-text-btn"
          @click="openDialog"
          >新建工作流</el-button
        >
      </div>
    </div>

    <!-- 卡片列表 -->
    <div class="card-list-flex">
      <div class="workflow-card" v-for="card in workflows" :key="card.id">
        <div class="card-header">
          <div class="avatar-bg">
            <el-avatar
              :src="card.icon || defaultAvatar"
              :size="36"
              style="background: transparent"
              @error="(e) => (e.target.src = defaultAvatar)"
            />
          </div>
          <div class="card-info">
            <div class="card-title">{{ card.name }}</div>
            <div class="card-sub">{{ card.count }}</div>
          </div>
        </div>
        <div class="card-actions">
          <div class="action-item">
            <el-button
              icon="el-icon-edit-outline"
              size="mini"
              circle
              class="action-btn"
              @click="goDesign(card)"
            />
            <span
              class="action-label"
              @click="goDesign(card)"
              style="cursor: pointer"
              >设计</span
            >
          </div>
          <div class="action-item">
            <el-button
              icon="el-icon-download"
              size="mini"
              circle
              class="action-btn"
              @click="handleExport(card)"
            />
            <span
              class="action-label"
              @click="handleExport(card)"
              style="cursor: pointer"
              >导出</span
            >
          </div>
          <div class="action-item">
            <el-button
              icon="el-icon-caret-right"
              size="mini"
              circle
              class="action-btn"
              @click="goRun(card)"
            />
            <span
              class="action-label"
              @click="goRun(card)"
              style="cursor: pointer"
              >运行</span
            >
          </div>
          <div class="action-item">
            <el-button
              icon="el-icon-edit"
              size="mini"
              circle
              class="action-btn"
              @click="handleEdit(card)"
            />
            <span
              class="action-label"
              @click="handleEdit(card)"
              style="cursor: pointer"
              >编辑</span
            >
          </div>
          <el-dropdown>
            <div class="action-item">
              <el-button
                icon="el-icon-more"
                size="mini"
                circle
                class="action-btn"
              />
              <span class="action-label">更多</span>
            </div>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item @click.native="handleDelete(card)"
                >删除</el-dropdown-item
              >
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>
    </div>

    <el-dialog
      :visible.sync="dialogVisible"
      :title="isEdit ? '编辑工作流' : '新增工作流'"
      width="600px"
      @close="handleDialogCancel"
      append-to-body
    >
      <el-form
        :model="form"
        :rules="rules"
        ref="workflowForm"
        label-width="90px"
      >
        <el-form-item label="Icon:">
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :before-upload="handleIconUpload"
            action="#"
          >
            <div v-if="!form.icon" class="icon-upload-btn">
              <i class="el-icon-plus" style="font-size: 32px"></i>
              <div>上传</div>
            </div>
            <img
              v-else
              :src="form.icon"
              class="icon-preview"
              @error="(e) => (e.target.src = defaultAvatar)"
            />
          </el-upload>
        </el-form-item>
        <el-form-item label="名称:" prop="name" required>
          <el-input v-model="form.name" placeholder="请输入工作流名称" />
        </el-form-item>
        <el-form-item label="英文名称:" prop="ename" required>
          <el-input
            v-model="form.ename"
            placeholder="请输入英文名称,不允许含中文"
          />
        </el-form-item>
        <el-form-item label="描述:" prop="desc" required>
          <el-input
            type="textarea"
            v-model="form.desc"
            placeholder="请输入工作流描述，便于大模型更好理解并调用"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleDialogCancel">取消</el-button>
        <el-button type="primary" @click="handleDialogOk">{{
          isEdit ? "保存" : "新增"
        }}</el-button>
      </div>
    </el-dialog>

    <!-- 导入工作流弹窗 -->
    <el-dialog
      :visible.sync="importDialogVisible"
      title="导入工作流"
      width="600px"
      @close="handleImportDialogCancel"
      append-to-body
    >
      <el-form
        :model="importForm"
        :rules="importRules"
        ref="importForm"
        label-width="90px"
      >
        <el-form-item label="名称:" prop="name" required>
          <el-input v-model="importForm.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="描述:" prop="desc">
          <el-input
            type="textarea"
            v-model="importForm.desc"
            placeholder="请输入描述"
            :rows="3"
          />
        </el-form-item>
        <el-form-item label="文件:" prop="file" required>
          <el-upload
            action="#"
            :show-file-list="false"
            :before-upload="handleImportFileChange"
            accept=".json"
          >
            <el-button icon="el-icon-upload">选择文件</el-button>
            <span v-if="importForm.file" style="margin-left: 10px">{{
              importForm.file.name
            }}</span>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleImportDialogCancel">取消</el-button>
        <el-button type="primary" @click="handleImportDialogOk">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listWorkflow,
  addWorkflow,
  updateWorkflow,
  delWorkflow,
  delWorkflowBatch,
  importWorkflow,
  exportWorkflow,
} from "@/api/system/workflow";
import { upload } from "@/api/system/common";
import axios from "axios";
import workflowIcon from "@/assets/workflowIcon.png";
import defaultAvatar from "@/assets/avatar/ai.png";
export default {
  name: "WorkflowIndex",
  data() {
    return {
      search: {
        name: "",
        ename: "",
      },
      dialogVisible: false,
      isEdit: false,
      form: {
        icon: "",
        name: "",
        ename: "",
        desc: "",
      },
      workflows: [], // 改为后端数据
      rules: {
        name: [
          { required: true, message: "请输入工作流名称", trigger: "blur" },
        ],
        ename: [
          { required: true, message: "请输入英文名称", trigger: "blur" },
          {
            pattern: /^[A-Za-z0-9_]+$/,
            message: "只能输入英文和数字",
            trigger: "blur",
          },
        ],
        desc: [{ required: true, message: "请输入描述", trigger: "blur" }],
      },
      defaultAvatar: workflowIcon,
      importDialogVisible: false,
      importForm: {
        name: "",
        desc: "",
        file: null,
      },
      importRules: {
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
        file: [
          { required: true, message: "请选择JSON文件", trigger: "change" },
        ],
      },
    };
  },
  mounted() {
    this.loadWorkflows();
  },
  methods: {
    loadWorkflows() {
      listWorkflow(this.search)
        .then((res) => {
          if (res.code === 200) {
            // 兼容后端返回的 id 字段问题
            this.workflows = (res.rows || res.data || []).map((item) => ({
              ...item,
              id: item.id || item.workflowId, // 兼容不同字段
            }));
          } else {
            this.$message.error("加载工作流列表失败: " + res.msg);
          }
        })
        .catch((error) => {
          this.$message.error("加载工作流列表失败: " + error.message);
        });
    },
    handleSearch() {
      this.loadWorkflows();
    },
    handleReset() {
      this.search.name = "";
      this.search.ename = "";
      this.loadWorkflows();
    },
    openDialog() {
      this.isEdit = false;
      this.dialogVisible = true;
      this.form = { icon: "", name: "", ename: "", desc: "" };
      this.$nextTick(() => {
        if (this.$refs.workflowForm) this.$refs.workflowForm.resetFields();
      });
    },
    handleDialogOk() {
      this.$refs.workflowForm.validate((valid) => {
        if (valid) {
          if (this.isEdit && this.form.id) {
            updateWorkflow(this.form).then(() => {
              this.$message.success("修改成功");
              this.dialogVisible = false;
              this.isEdit = false;
              this.loadWorkflows();
            });
          } else {
            addWorkflow(this.form).then(() => {
              this.$message.success("新增成功");
              this.dialogVisible = false;
              this.isEdit = false;
              this.loadWorkflows();
            });
          }
        }
      });
    },
    handleDialogCancel() {
      this.dialogVisible = false;
      this.isEdit = false;
      this.form = { icon: "", name: "", ename: "", desc: "" };
    },
    handleIconUpload(file) {
      const realFile = file.raw || file;
      if (!realFile.type.startsWith("image/")) {
        this.$message.error("只能上传图片文件");
        return false;
      }
      const formData = new FormData();
      formData.append("file", realFile);
      upload(formData)
        .then((res) => {
          const url = res.url || res.data?.url || res.data?.data?.url;
          if (url) {
            this.form.icon = url;
            // 删除对 this.workflows 的直接修改，不再实时刷新卡片头像
          } else {
            this.$message.error("上传失败");
          }
        })
        .catch((err) => {
          this.$message.error("上传失败");
        });
      return false;
    },
    openImportDialog() {
      this.importDialogVisible = true;
      this.$nextTick(() => {
        if (this.$refs.importForm) this.$refs.importForm.resetFields();
        this.importForm.file = null;
      });
    },
    handleImportFileChange(file) {
      const realFile = file.raw || file;
      const isJson =
        realFile.type === "application/json" || realFile.name.endsWith(".json");
      if (!isJson) {
        this.$message.error("只能上传JSON文件");
        return false;
      }
      this.importForm.file = realFile;
      return false; // 阻止自动上传
    },
    handleImportDialogOk() {
      this.$refs.importForm.validate((valid) => {
        if (valid) {
          const reader = new FileReader();
          reader.onload = (e) => {
            let json;
            try {
              json = JSON.parse(e.target.result);
            } catch (err) {
              this.$message.error("JSON文件格式错误");
              return;
            }
            // 去除id字段
            if (json.id) delete json.id;
            if (json.workflowId) delete json.workflowId;
            // ename添加随机后缀，确保唯一
            if (json.ename) {
              json.ename =
                json.ename + "_" + Math.random().toString(36).substr(2, 5);
            }
            // 这里强制设置icon为默认头像
            json.icon = this.defaultAvatar;
            const blob = new Blob([JSON.stringify(json)], {
              type: "application/json",
            });
            const formData = new FormData();
            formData.append("file", blob, this.importForm.file.name);
            formData.append("name", this.importForm.name);
            formData.append("desc", this.importForm.desc);
            importWorkflow(formData).then((res) => {
              this.$message.success("导入成功");
              this.importDialogVisible = false;
              this.loadWorkflows();
            });
          };
          reader.readAsText(this.importForm.file);
        }
      });
    },
    handleImportDialogCancel() {
      this.importDialogVisible = false;
    },
    goDesign(card) {
      if (!card.id) {
        this.$message.error("工作流ID无效，无法进入设计页面");
        return;
      }
      this.$router.push(`/workflow/design/${card.id}`);
    },
    goRun(card) {
      if (!card.id) {
        this.$message.error("工作流ID无效，无法进入运行页面");
        return;
      }
      this.$router.push("/workflow/run");
    },
    handleEdit(card) {
      this.isEdit = true;
      this.form = { ...card };
      this.dialogVisible = true;
      this.$nextTick(() => {
        if (this.$refs.workflowForm) this.$refs.workflowForm.clearValidate();
      });
    },
    handleExport(card) {
      exportWorkflow(card.id)
        .then((res) => {
          if (res && res.code === 200 && res.data) {
            const blob = new Blob([JSON.stringify(res.data, null, 2)], {
              type: "application/json",
            });
            const url = URL.createObjectURL(blob);
            const a = document.createElement("a");
            a.href = url;
            a.download = `${
              res.data.ename || res.data.name || "workflow"
            }.json`;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
            this.$message.success("导出成功");
          } else {
            this.$message.error("导出失败: " + (res.msg || "未知错误"));
          }
        })
        .catch((error) => {
          this.$message.error("导出失败: " + error.message);
        });
    },
    handleDelete(card) {
      this.$confirm("确定要删除该工作流吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delWorkflow(card.id).then(() => {
            this.$message.success("删除成功");
            this.loadWorkflows();
          });
        })
        .catch(() => {
          // 取消删除
        });
    },
  },
};
</script>

<style scoped>
.workflow-page {
  background: #fafafa;
  min-height: 100vh;
  padding: 24px;
}
.breadcrumb {
  margin-bottom: 18px;
}
.search-bar {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  background: transparent;
  padding: 0 0 8px 0;
  margin-bottom: 18px;
}
.search-form {
  background: #fff;
  border-radius: 8px;
  padding: 12px 18px 0 18px;
  min-width: 700px;
}
.right-btns {
  display: flex;
  gap: 8px;
  margin-top: 2px;
}
.top-btn {
  font-size: 13px;
  padding: 7px 16px;
  border-radius: 6px;
  font-weight: 500;
}
.card-list-flex {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(340px, 1fr));
  gap: 24px;
  margin-top: 0;
  width: 100%;
  box-sizing: border-box;
}
.workflow-card {
  width: 100%;
  min-width: 340px;
  max-width: 100%;
  box-sizing: border-box;
  border-radius: 14px;
  min-height: 110px;
  box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.04);
  border: none;
  margin-bottom: 0;
  padding: 0 0 8px 0;
}
.card-header {
  display: flex;
  align-items: center;
  gap: 14px;
  margin-bottom: 8px;
  padding: 18px 0 0 18px;
}
.avatar-bg {
  width: 44px;
  height: 44px;
  background: #e6f0fb;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}
.card-info {
  display: flex;
  flex-direction: column;
  justify-content: center;
}
.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #222;
  line-height: 1.2;
}
.card-sub {
  color: #8c8c8c;
  font-size: 13px;
  margin-top: 2px;
}
.action-item {
  display: flex;
  align-items: center;
  margin-right: 10px;
  white-space: nowrap;
  max-width: 70px; /* 限制最大宽度，按实际调整 */
  overflow: hidden;
}
.action-label {
  margin-left: 4px;
  font-size: 13px;
  color: #666;
  cursor: pointer;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 40px; /* 限制文字宽度，按实际调整 */
  display: inline-block;
}
.action-label:hover {
  color: #409eff;
}
.card-actions {
  display: flex;
  align-items: center;
  padding-left: 18px;
  padding-bottom: 6px;
  gap: 8px;
  flex-wrap: wrap; /* 允许换行 */
  overflow: hidden; /* 防止极端溢出 */
}
.action-btn {
  background: #f4f6fa;
  color: #8c8c8c;
  border: none;
  margin-right: 2px;
  transition: background 0.2s;
}
.action-btn:hover {
  background: #e6f0fb;
  color: #409eff;
}
.white-text-btn {
  color: #fff !important;
}
.white-text-btn:hover,
.white-text-btn:focus {
  color: #fff !important;
}
.ename-input {
  width: 320px;
  max-width: 100%;
}
.icon-upload-btn {
  width: 120px;
  height: 120px;
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #999;
  cursor: pointer;
  font-size: 24px;
  margin: 0 auto 10px auto;
}
.icon-preview {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  object-fit: cover;
  display: block;
  margin: 0 auto 10px auto;
}
</style>